package compendiumAid.presentation.exportElements
{
	import compendiumAid.application.Element;
	import compendiumAid.application.exportElements.ExportElementsEvent;
	import compendiumAid.application.exportElements.ExportElementsInitEvent;
	import compendiumAid.application.loadElement.LoadElementEvent;
	import compendiumAid.domain.ApplicationCursorManager;
	import compendiumAid.domain.Constants;
	import compendiumAid.domain.model.ApplicationModel;
	import compendiumAid.domain.vo.ElementVO;
	import compendiumAid.presentation.PresentationModel;
	import compendiumAid.presentation.elementView.ElementComponent;
	
	import mx.collections.ArrayCollection;
	
	import spark.components.HGroup;
	import spark.components.VGroup;
	
	public class ExportElementsPM extends PresentationModel
	{
		[Inject]
		[Bindable]
		public var model:ApplicationModel;
		
		[Bindable]
		public var elements:ArrayCollection;
		
		private var currentWindow:ExportElements;
		private var elementRows:ArrayCollection;
		
		[MessageHandler]
		public function openWindow(event:ExportElementsInitEvent):void
		{
			ApplicationCursorManager.setBusyCursor();
			
			this.elements = event.elements;
			
			var group:VGroup = createElementsGroup();
			
			currentWindow = new ExportElements;
			currentWindow.pm = this;
			currentWindow.open();
			currentWindow.visible = false;
			currentWindow.addElementsGroup(group);
			currentWindow.visible = true;
			
			ApplicationCursorManager.removeBusyCursor();
		}
		
		public function export():void
		{
			dispatcher(new ExportElementsEvent(elementRows));
			
			//close();
		}
		
		public function close():void
		{
			currentWindow.close();
			currentWindow.pm = null;
			currentWindow = null;
		}
		
		private function createElementsGroup():VGroup
		{
			var index:Number = 0;
			var rowGroup:VGroup = new VGroup;
			
			rowGroup.percentHeight = 100;
			rowGroup.percentWidth = 100;
			rowGroup.gap = 0;
			
			elementRows = new ArrayCollection;
			
			for (var x:Number = 0; x < (elements.length / model.elementsPerRow); x++)
			{
				var row:HGroup = new HGroup();
				row.gap = 0;
				row.width = model.elementsPerRow * Constants.ELEMENT_WIDTH;
				
				rowGroup.addElement(row);
				elementRows.addItem(row);
				
				for (var y:Number = 0; y < model.elementsPerRow; y++)
				{
					var element:Element = new Element(elements.getItemAt(index) as ElementVO);
					
					dispatcher(new LoadElementEvent(element));
					
					var elementComponent:ElementComponent = new ElementComponent();
					elementComponent.element = element;
					elementComponent.cssString = model.cssString;
					
					row.addElement(elementComponent);

					index++;
					
					if (index >= elements.length) break;
				}
			}
			
			return rowGroup;
		}
	}
}